package com.atguigu.yeb.server.service.impl;

import com.atguigu.yeb.server.base.R;
import com.atguigu.yeb.server.pojo.entity.TAdmin;
import com.atguigu.yeb.server.mapper.TAdminMapper;
import com.atguigu.yeb.server.security.JWTUtils;
import com.atguigu.yeb.server.service.TAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huafeng
 * @since 2021-12-04
 */
@Service
public class TAdminServiceImpl extends ServiceImpl<TAdminMapper, TAdmin> implements TAdminService {

    @Autowired
    private UserDetailsService udtailservice;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private TAdminMapper tAdminMapper;
    @Autowired
    private JWTUtils jwtUtils;
    @Value("${jwt.tokenHead}")
    String tokenHead;

    //判断登陆  使用的类：UserDetailsService、PasswordEncoder、JWTUtils；参数：jwt.tokenHead
    @Override
    public R login(String username, String password, HttpServletRequest request) {
        //得到一个UserDetails对象
        UserDetails userDetails = udtailservice.loadUserByUsername(username);
        //用户名为空或者密码不匹配
        if (null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return R.error().message("用户不存在或者密码不正确");
        }
        //用户状态是否被禁用
        if (!userDetails.isEnabled()){
            return R.error().message("用户被禁用，请联系管理员");
        }
        //使用了security，暂时不明白
        UsernamePasswordAuthenticationToken adminToken = new UsernamePasswordAuthenticationToken(userDetails,
                null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(adminToken);

        //创建token并返回
        String token = jwtUtils.generateToken(userDetails);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);

        return R.ok().message("登陆成功").data("token",map);
    }
    //根据用户名获取信息
    @Override
    public TAdmin getUserByName(String name) {
        QueryWrapper<TAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",name);
        TAdmin tAdmin = tAdminMapper.selectOne(queryWrapper);
        return tAdmin;
    }
}
